import {ActionContext} from 'vuex'

const ATTR_USER_TOKEN = "user_token";
const ATTR_USER_TOKEN_EXPIRED = "user_token_expired";
const ATTR_TEMP_USER_ID = "temp_user_id";
export default {
    namespaced: true,
    state: {
        token: uni.getStorageSync(ATTR_USER_TOKEN),
        tokenExpired: uni.getStorageSync(ATTR_USER_TOKEN_EXPIRED),
        tempUserId:uni.getStorageSync(ATTR_TEMP_USER_ID),
        logined:false,
        userInfo: {}
    },
    getters: {
        isTokenValid(state:any) {
            return !!state.token && !!state.tokenExpired && state.tokenExpired > Date.now()
        }
    },
    mutations: {
        SET_TEMP_USER_ID:(state:any, tempUserId:string) => {
           state.tempUserId = tempUserId
           uni.setStorageSync(ATTR_TEMP_USER_ID, tempUserId)
        },
        SET_LOGIN_INFO:(state:any, loginInfo:any) => {
            loginInfo = loginInfo || {}
            const tokenInfo = loginInfo.tokenInfo || {}
            const tokenExpired = tokenInfo.token  && tokenInfo.expireTime ? new Date(tokenInfo.expireTime) : undefined
            state.token = tokenInfo.token
            state.tokenExpired = tokenExpired
            state.userInfo = loginInfo.userInfo || {}
            uni.setStorageSync(ATTR_USER_TOKEN, tokenInfo.token)
            uni.setStorageSync(ATTR_USER_TOKEN_EXPIRED, tokenExpired)
            state.logined = loginInfo.success

        }
    },
    actions: {
		logout({
			commit
		}:ActionContext<any,any>) {
			commit('SET_LOGIN_INFO', {success:false})
            console.log('已退出登录')
		},
        setLoginResult({
			commit
		}:ActionContext<any,any>,loginResult:any) {
			commit('SET_LOGIN_INFO', loginResult)
		}
	}
}
